#include <iostream>
#include <mutex>
#include <condition_variable>
#include <deque>
#include <thread>
std::mutex mutex;
std::condition_variable cond;
int c = 0;
struct task {
    task(int value) : v(value) {}
    void operator=(const task& t) {
        this->v = t.v;
    }
    int v;
};
std::deque<task> cache;


void consumer()
{
    while (true) {
        task t(0);
        {
            std::unique_lock<std::mutex> lck(mutex);//c++是使用unique_lock和cond配合使用
            //防止虚假唤醒
            while (cache.empty()) {
                cond.wait(lck);
            }
            t = cache.front();
            cache.pop_front();
            std::cout << "线程: " << std::this_thread::get_id() << "正在处理任务" << t.v << std::endl;
        }
        //处理

        
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }

}
void producer()
{
    while (true) {
        {
            std::unique_lock<std::mutex> lck(mutex);
            cache.emplace_back(c++);
            cache.emplace_back(c++);
            cache.emplace_back(c++);
            cache.emplace_back(c++);
            cond.notify_all();
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }

}

int main()
{
    std::thread t1(producer);
    std::thread t2(consumer);
    std::thread t3(consumer);

    t1.join();
    t2.join();
    t3.join();
    return 0;
}